package com.example.demo.listener;

import cn.hutool.core.date.DateUtil;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * session监听器
 *
 * @author Administrator
 */
@WebListener
public class SessionListener implements HttpSessionListener {

    /**
     * 记录session的数量
     */
    private int onlineCount = 0;

    /**
     * session创建后执行
     */
    @Override
    public void sessionCreated(HttpSessionEvent session) {
        System.out.println("监听-> Session创建成功,SessionID:" + session.getSession().getId() + "时间:" + DateUtil.now());
        onlineCount++;
        System.out.println("在线Session个数:" + onlineCount);
        session.getSession().getServletContext().setAttribute("onlineCount", onlineCount);
    }

    /**
     * session失效后执行
     */
    @Override
    public void sessionDestroyed(HttpSessionEvent session) {
        System.out.println("监听-> Session销毁,SessionID:" + session.getSession().getId() + "时间:" + DateUtil.now());
        if (onlineCount > 0) {
            onlineCount--;
        }
        System.out.println("在线Session个数:" + onlineCount);
        session.getSession().getServletContext().setAttribute("onlineCount", onlineCount);
    }

}
